import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLoginOut} from "@/api"
import {setToken ,getToken, removeToken} from '@/utils/token.js'

const namespaced = true
const state = {
  code: '',
  token: getToken(),
  userInfo: {}
}
const actions = {
  // 获取验证码
  async getCodePhone({ commit }, phone) {
    let result = await reqGetCode(phone)
    if (result.code === 200) {
      commit('GETCODE', result.data)
      return 'ok'
    } else {
      return Promise.reject(new Error('err'))
    }
  },
  // 注册
  async postUserRegister({commit}, data){
   let result = await reqUserRegister(data)
   if (result.code === 200) {
     return 'ok'
   }else {
     return Promise.reject(result.message)
   }
  },
  // 登陆
  async postUserLogin({commit}, data){
    let result = await reqUserLogin(data)
    if (result.code === 200) {
      commit('USERTOCK', result.data.token)
      return result.message
    } else {
      return Promise.reject(result.message)
    }
  },
  // 获取 用户信息
  async getUserInfo({ commit }) {
    let result = await reqUserInfo()
    if (result.code === 200) {
      commit('GETUSERINFO', result.data)
      return 'ok'
    }else {
      return Promise.reject(result.message)
    }
  },
  // 退出登陆
  async loginOut({commit}){
    let result =  await reqLoginOut()
    if (result.code === 200) {
      commit('LOGINOUT')
      return result.message
    }else {
      return Promise.reject(result.message)
    }
  }
}

const mutations = {
  // 存放验证码
  GETCODE(state, code) {
    state.code = code
  },
  // 存放token
  USERTOCK(state, token){
    state.token = token
    // 存入本地 token
    setToken(token)
  },
  // 存放用户信息
  GETUSERINFO(state, userInfo) {
    state.userInfo = userInfo
  },
  // 退出登陆
  LOGINOUT(state) {
    state.token = '',
    state.userInfo = {},
    removeToken()
  }
}

const getters = {}


export default {
  namespaced,
  state,
  actions,
  mutations,
  getters,
}
